package com.wang.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.controller.utils.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname JWTInterceptor
 * @Description TODO
 * @Date 2024/10/9 16:16
 * @Created by pc
 */
public class JWTInterceptor implements HandlerInterceptor {
    // 表示所有请求到达之前 拦截器工作对请求进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // 拦截的目的是为了从请求的头部获取token 判断token 是否有效
        String token = request.getHeader("token");
        Map<String,Object> map = new HashMap<>();
        try {
            DecodedJWT verify = JWTUtil.verify(token);
            map.put("status",true);
            map.put("msg","请求成功");
            // 拦截放行
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "无效签名!");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期!");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效");
        }
        map.put("status", false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
        // 拦截不放行
        return false;
    }
}
